
from flask import Blueprint, redirect,render_template, request, url_for
from app.models.base import db
from app.models.admin import Admin
from app.models.request import Request
from app.models.assignqV import AssignmentQ
from app.models.llmAnswer import LLMAnswer
from app.models.experiment import Experiment
from app.models.course import Course

adminBP = Blueprint('admin',__name__)

@adminBP.route('/add_course', methods=['GET'])
def view_add_course_requests():
    add_course_requests=Request.query.filter(Request.Request_Type=="ADD_COURSE", Request.Approve_Type=='wait').all()
    print(add_course_requests)
    return render_template('handle_course.html', requests=add_course_requests,name="Admin")


@adminBP.route('/update_score')
def view_update_score_requests():
    results=[]
    update_score_requests=Request.query.filter(Request.Request_Type=="UPDATE_SCORE", Request.Approve_Type=='wait').all()
    
    for request in update_score_requests:
        for LLM_Answer in LLMAnswer.query.filter(request.A_ID == LLMAnswer.A_id).all():
            for Qtext in AssignmentQ.query.filter(LLM_Answer.Q_id == AssignmentQ.Q_id).all():
                results.append({
                    'RequestID' : request.RequestID,
                    'Q_text': Qtext.Q_Text,
                    'A_ID' : LLM_Answer.LLM_Answer,
                    'ScoreUpdateCount' : request.ScoreUpdateCount,
                    'Explanation' : request.Explanation,
                    'Request_Type' : request.Request_Type,
                    'Approve_Type' : request.Approve_Type

                })
    print(results)
    return render_template('handle_UpdateScore.html', results=results)


@adminBP.route('/add_experiment')
def view_add_experiment_requests():
    results=[]
    add_experiment_requests =Request.query.filter(Request.Request_Type=="ADD_EXPERIMENT", Request.Approve_Type=='wait').all()
    for request in add_experiment_requests:
        for experiments in Experiment.query.filter(request.EID == Experiment.E_id).all():
            
                results.append({
                    'RequestID' : request.RequestID,
                    'EID': experiments.question_text,
                    'answer_image_path' : experiments.answer_image_path,
                    'Explanation' : request.Explanation,
                    'Request_Type' : request.Request_Type,
                    'Approve_Type': request.Approve_Type

                })
    return render_template('handle_experiment.html', results=results)


def handle_add_course(request):
    # 创建新的 Course 对象
    new_course = Course(
        CNumber=None,
        CName=request.CourseName,
        CCategory=request.CourseCategory
    )
    with db.auto_commit():
        db.session.add(new_course)
    print(f"Added course: {request.CourseName}")

def handle_update_score(request):
    a_id = int(request.A_ID)
    llm_answer = LLMAnswer.query.filter_by(A_id=a_id).first()
    if llm_answer:
        score_update_count = float(request.ScoreUpdateCount)
        # 计算新的 LLM_Score
        new_score = (llm_answer.Score + score_update_count) / 2.0
        # 更新 LLM_Score
        llm_answer.Score = new_score
        db.session.commit()
    print(f"Updated score to LLMAnswer with AID: {a_id}")


def handle_add_experiment(request):
    eid = int(request.EID)
    # 查找 Experiment 中对应的记录
    experiment = Experiment.query.filter_by(E_id=eid).first()
    qid = db.session.query(AssignmentQ).count() + 1
    if experiment:
        # 创建新的 LLMAnswer 对象
        new_assignment_q= AssignmentQ(
            Q_id=qid,
            CNumber=experiment.course_number,
            Q_Text=experiment.question_text
            
        )
        
        new_llm_answer = LLMAnswer(
            A_id=None,  # 自动生成主键
            LLM_Name=experiment.LLMname,
            LLM_Answer=experiment.answer_image_path,  # Assuming answer_image_path as LLM_Answer
            Score=float(experiment.score),  # 确保为浮点数
            Comments=experiment.comments,
            Q_id=new_assignment_q.Q_id
        )
        # 添加到数据库会话并提交
        db.session.add(new_llm_answer)
        db.session.add(new_assignment_q)
        db.session.commit()
        print(f"Added experiment to Assignment_Q and LLMAnswer with EID: {eid}")

@adminBP.route('/approve/action/<int:request_id>/<string:action>', methods=['POST'])
def approve_request_action(request_id, action):
    request = Request.query.get(request_id)
    if request:
        if action == 'pass':
            if request.Request_Type == 'ADD_COURSE':
                handle_add_course(request)
                request.Approve_Type = 'pass'
                db.session.commit()
                return redirect(url_for('admin.view_add_course_requests'))
            elif request.Request_Type == 'UPDATE_SCORE':
                handle_update_score(request)
                request.Approve_Type = 'pass'
                db.session.commit()
                return redirect(url_for('admin.view_update_score_requests'))
            elif request.Request_Type == 'ADD_EXPERIMENT':
                handle_add_experiment(request)
                request.Approve_Type = 'pass'
                db.session.commit()
                return redirect(url_for('admin.view_add_experiment_requests'))
        elif action == 'reject':
            request.Approve_Type = 'reject'
            db.session.commit()
            # 根据 request_type 返回相应的页面
            if request.Request_Type == 'ADD_COURSE':
                return redirect(url_for('admin.view_add_course_requests'))
            elif request.Request_Type == 'UPDATE_SCORE':
                return redirect(url_for('admin.view_update_score_requests'))
            elif request.Request_Type == 'ADD_EXPERIMENT':
                return redirect(url_for('admin.view_add_experiment_requests'))